package com.luocc.ccdemo.vm

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.luocc.ccdemo.db.AppDatabase
import com.luocc.ccdemo.db.VideoRepository
import com.luocc.ccdemo.entity.Video
import com.luocc.ccdemo.utils.CommonUtil
import kotlinx.coroutines.launch

private const val TAG = "VideoViewModel"
class VideoViewModel(application: Application) : AndroidViewModel(application) {
    private val mVideoRepository: VideoRepository
    private val mFavoritesVideo: LiveData<List<Video>>
    private val mVideoList: MutableLiveData<List<Video>> = MutableLiveData()
    private val mVideoEmpty: MutableLiveData<Boolean> = MutableLiveData()

    init {
        mVideoRepository = VideoRepository(application)
        mFavoritesVideo = mVideoRepository.getFavorites()
    }

    fun getFavorites(): LiveData<List<Video>> {
        return mFavoritesVideo
    }

    fun getVideoList(): LiveData<List<Video>> {
        return mVideoList
    }

    fun getVideoEmpty(): LiveData<Boolean> {
        return mVideoEmpty
    }

    fun insert(video: Video) {
        video.insertTime = CommonUtil.getCurrentDate()
        AppDatabase.databaseWriteExecutor.execute {
            mVideoRepository.insert(video)
        }
    }

    fun update(video: Video) {
        AppDatabase.databaseWriteExecutor.execute {
            mVideoRepository.update(video)
        }
    }

    fun clearFavorites() {
        AppDatabase.databaseWriteExecutor.execute {
            mVideoRepository.clearFavorites()
        }
    }

    fun delete(id: Int) {
        viewModelScope.launch {
            mVideoRepository.delete(id)
        }
    }

    fun getVideo(size: Int) {
        Log.d(TAG, "getVideo 1")
        viewModelScope.launch {
            var list: List<Video>? = null
            try {
                Log.d(TAG, "getVideo 2")
                val result = mVideoRepository.getVideo(size)
                if (result.code == 200) {
                    result.data?.let {
                        list = it.getParcelableArrayList("videos")
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            if (list.isNullOrEmpty()) {
                mVideoEmpty.value = true
            } else {
                mVideoList.value = list
            }
        }
    }
}